package org.lzz.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.lzz.mapper.ArticleMapper;
import org.lzz.pojo.Article;
import org.lzz.pojo.PageBean;
import org.lzz.service.ArticleService;
import org.lzz.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer UserId = (Integer) map.get("id");
        article.setCreateUser(UserId);

        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 1. 创建PageBean对象
        PageBean<Article> pb = new PageBean<>();

        // 2. 开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);

        // 3. 调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer UserId = (Integer) map.get("id");
        List<Article> ls =  articleMapper.list(UserId,categoryId,state);

        // Page中提供了方法可以获取PageHelper分页查询得到的总记录条数和当前页数据
        Page<Article> p = (Page<Article>) ls;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());

        return pb;
    }

    @Override
    public Article findById(Integer id) {
        return articleMapper.findById(id);
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
